package com.changgou.oauth.controller;


import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.oauth.service.UserLoginService;
import com.changgou.oauth.util.AuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserLoginController {

    @Autowired
    private UserLoginService userLoginService;

    @Value("${auth.clientId}")
    private String clientId;


    @Value("${auth.clientId}")
    private String clientSecret;

    /**
     * 通过密码认证
     *
     * @param username 用户名
     * @param password 密码
     * @return token
     */
    @RequestMapping("/login")
    public Result login(String username, String password, HttpServletResponse response) {
        if (StringUtils.isEmpty(username)) {
            throw new RuntimeException("用户名不允许为空");
        }
        if (StringUtils.isEmpty(password)) {
            throw new RuntimeException("密码不允许为空");
        }

        try {
            String grant_type = password;
            AuthToken authToken = userLoginService.login(clientId, clientSecret, username, password);
            String token = authToken.getAccessToken();
            String tokenType = authToken.getTokenType();
            // 注意：这里的token并没有bearer字符串，在过滤器那里需要拼接

            Cookie cookie = new Cookie("Authorization",  token);
            cookie.setDomain("www.changgou.com");
            cookie.setPath("/");
            response.addCookie(cookie);


            return new Result(true, StatusCode.OK, "登录成功！", authToken);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.OK, "登录失败！");
        }

    }


}
